package com.hengtiansoft.lfy.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.LoginInfo;
import com.hengtiansoft.lfy.entity.OtherUserRegisterInfo;
import com.hengtiansoft.lfy.entity.RequestRegister;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.TokenInfo;
import com.hengtiansoft.lfy.entity.UserInfo;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.Utils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;


/**
 * Created by daiye on 2016/10/27 0027.
 */

public class LoginActivity extends BaseActivity {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private final int ACTIVITY_RESULT_REGISTER = 1;
    private final int ACTIVITY_RESULT_FORGET_PASSWORD = 2;
    private TextView mTvSkip;
    private EditText mUserNameEt;
    private EditText mPasswordEt;
    private Button mLoginBt;
    private TextView mRegisterTv;
    private TextView mForgetPasswordTv;

    private ImageView mWeixinIb;
    private ImageView mWeiboIb;
    private ImageView mQQIb;

    private int third_login=1;

    private String userNameStr="";
    private String passwordStr="";

    // 整个平台的UMShareAPI,负责管理整个SDK的配置、操作等处理
    private UMShareAPI mShareAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initData(){

    }

    private void initView() {
        setContentView(R.layout.activity_login);
        mTvSkip =  (TextView) findViewById(R.id.tv_skip);
        mTvSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mUserNameEt = (EditText) findViewById(R.id.username_et);
        mPasswordEt = (EditText) findViewById(R.id.password_et);
        mLoginBt = (Button) findViewById(R.id.login_bt);
        mRegisterTv = (TextView)findViewById(R.id.register_tv);
        mForgetPasswordTv = (TextView)findViewById(R.id.forget_password_tv);

        mLoginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mLoginBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mLoginBt, 0);
                processLogin(false,null);
            }
        });
        mRegisterTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mLoginBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mLoginBt, 0);
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivityForResult(intent, ACTIVITY_RESULT_REGISTER);
            }
        });
        mForgetPasswordTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mLoginBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mLoginBt, 0);
                Intent intent = new Intent(LoginActivity.this, PasswordForgetActivityV2.class);
                startActivityForResult(intent, ACTIVITY_RESULT_FORGET_PASSWORD);
            }
        });

        mWeixinIb = (ImageView) findViewById(R.id.iv_login_weixin);
        mWeiboIb = (ImageView) findViewById(R.id.iv_login_weibo);
        mQQIb = (ImageView) findViewById(R.id.iv_login_qq);

        mShareAPI = UMShareAPI.get(this);

        mWeixinIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                third_login = 1;
                login(SHARE_MEDIA.WEIXIN);
            }
        });
        mWeiboIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                third_login = 2;
                login(SHARE_MEDIA.SINA);
            }
        });
        mQQIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                third_login = 3;
                login(SHARE_MEDIA.QQ);
            }
        });

        mPasswordEt.setTypeface(Typeface.DEFAULT);
        mPasswordEt.setTransformationMethod(new PasswordTransformationMethod());

        if(Config.isUserLogined()){
            mUserNameEt.setText(Config.getUserName());
        }
    }

    /**
     * 登录自己服务器
     *
     * @param
     */
    private void processLogin(final boolean isOtherLogin, final RequestRegister requestRegister){
        if(isOtherLogin){
            userNameStr = requestRegister.getOpenid();
        }else{
            userNameStr= mUserNameEt.getText().toString();
            passwordStr= mPasswordEt.getText().toString();
            if(TextUtils.isEmpty(userNameStr) ){
                Toast.makeText(this, R.string.login_username_empty_tips, Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(passwordStr) ){
                Toast.makeText(this, R.string.login_password_empty_tips, Toast.LENGTH_SHORT).show();
                return;
            }
        }

        final String pas = passwordStr;

        userLogin(false);
    }

    /**
     * 授权。如果授权成功，则获取用户信息
     *
     * @param platform
     */
    private void login(final SHARE_MEDIA platform) {
        mShareAPI.doOauthVerify(this, platform,
                new UMAuthListener() {
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, final Map<String, String> map) {

                        LoginActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (map.size() > 0) {
                                    getUserInfo(platform);
                                } else {
                                    Log.i(TAG, "获取信息失败...");
                                    Toast.makeText(LoginActivity.this, getString(R.string.Authority_fail),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        Toast.makeText(LoginActivity.this, getString(R.string.Authority_fail),
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        Toast.makeText(LoginActivity.this, getString(R.string.Authority_canel),
                                Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    /**
     * 获取用户信息
     *
     * @param platform
     */
    private void getUserInfo(SHARE_MEDIA platform) {
        mShareAPI.getPlatformInfo(LoginActivity.this, platform,
                new UMAuthListener() {
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int status, Map<String, String> info) {
                        if (status == 2 & info != null) {
                            Log.i(TAG, info.toString());
                            thirdLogin(info);
                        } else {
                            Log.i(TAG, "获取信息失败...");
                        }
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {

                    }
                }
        );
    }

    /**
     * 第三方登录数据解析
     */
    private void thirdLogin(Map<String, String> map) {
        if (third_login == 1) { //微信
            String s1="";
            String avatarUrl="";
            if(!"".equals(map.get("headimgurl").toString())){
                s1= map.get("headimgurl").toString().substring(0,
                        map.get("headimgurl").toString().lastIndexOf("0"));
                avatarUrl= s1 + "132";
            }
            String upSex = null;
            int sex = Integer.parseInt(map.get("sex"));
            if (sex == 1) {
                upSex = "1";
            } else if (sex == 2) {
                upSex = "0";
            } else {
                upSex = null;
            }
            RequestRegister thirdLogin = new RequestRegister();
            thirdLogin.setOpenid(map.get("openid").toString());
            thirdLogin.setPicurl(avatarUrl);
            thirdLogin.setNickname(map.get("nickname").toString());
            thirdLogin.setType(third_login + "");
            thirdLogin.setGender(upSex);
            // thirdLogin.setSex(upSex);
            registerOtherUser(thirdLogin);
        } else if (third_login == 2) { //微博
            /*StringBuilder sb = new StringBuilder();
            Set<String> keys = map.keySet();
            for(String key : keys){
                sb.append(key+"="+map.get(key).toString()+"\r\n");
            }*/
            String upSex = null;
            String result=map.get("result");
            JSONObject jsonObject=null;
            try {
                jsonObject=new JSONObject(result);
                String sex = jsonObject.getString("gender");
                if (sex.equals("m")) {
                    upSex = "1";
                } else if (sex.equals("f")) {
                    upSex = "0";
                } else {
                    upSex = null;
                }
                RequestRegister thirdLogin = new RequestRegister();
                String uid="";
                uid=jsonObject.get("id").toString();
                thirdLogin.setOpenid(uid);
                thirdLogin.setPicurl(jsonObject.get("profile_image_url").toString());
                String name="";
                name=jsonObject.get("name").toString();
                thirdLogin.setNickname(name);
                thirdLogin.setType(third_login + "");
                thirdLogin.setGender(upSex);
                //thirdLogin.setSex(upSex);
                registerOtherUser(thirdLogin);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (third_login == 3) { //QQ
            String upSex = null;
            String sex = map.get("gender").toString();
            if (sex.equals("男")) {
                upSex = "1";
            } else if (sex.equals("女")) {
                upSex = "0";
            } else {
                upSex = null;
            }
            RequestRegister thirdLogin = new RequestRegister();
            thirdLogin.setOpenid(map.get("openid").toString());
            thirdLogin.setPicurl(map.get("profile_image_url").toString());
            thirdLogin.setNickname(map.get("screen_name").toString());
            thirdLogin.setType(third_login + "");
            thirdLogin.setGender(upSex);
            //  thirdLogin.setSex(upSex);
            registerOtherUser(thirdLogin);
        } else {
            Toast.makeText(this, getString(R.string.Authority_fail), Toast.LENGTH_SHORT).show();
        }
    }

    private void registerOtherUser(RequestRegister thirdLogin) {
        NetHelper.otherUserRegister(this, thirdLogin.getOpenid(), thirdLogin.getType(), thirdLogin.getNickname(),thirdLogin.getPicurl(),thirdLogin.getGender(),  new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                OtherUserRegisterInfo info = (OtherUserRegisterInfo) rspData;
                if (info.getRetcode() == 0 ) {
                    userNameStr = info.getData();
                    passwordStr = Constants.THIRDLOGINPASSWORD;
                    userLogin(true);
                    Toast.makeText(LoginActivity.this, info.getMessage(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, info.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        }, OtherUserRegisterInfo.class);
    }

    private void getUserToken(){
        NetHelper.getUserToken( LoginActivity.this, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                TokenInfo info = (TokenInfo)rspData;
                if (info.getRetcode() == 0) {
                    String token =  info.getData();
                    Config.setUserToken(token);
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    LoginActivity.this.finish();
                } else {
                    Toast.makeText(LoginActivity.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        }, TokenInfo.class);
    }

    private void userLogin(final boolean isOtherUserLogin){
        NetHelper.userLogin( LoginActivity.this,  userNameStr, Utils.MD5(passwordStr.trim()),  new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                LoginInfo info = (LoginInfo)rspData;
                if (info.getRetcode() == 0) {
                    UserInfo userInfo =  info.getUserInfo();
                    userInfo.setIsotheruser(isOtherUserLogin);
                    Config.setUserInfo(userInfo);
                    Toast.makeText(LoginActivity.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    getUserToken();
                } else {
                    Toast.makeText(LoginActivity.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        }, LoginInfo.class);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_REGISTER) {
            if (resultCode == Activity.RESULT_OK) {
                if(data!= null && data.hasExtra("UserName"))
                    mUserNameEt.setText( data.getStringExtra("UserName"));
                if(data!= null && data.hasExtra("Password"))
                    mPasswordEt.setText( data.getStringExtra("Password"));
            }
        }
        if(requestCode == ACTIVITY_RESULT_FORGET_PASSWORD){
            if (resultCode == Activity.RESULT_OK) {
                if(data!= null && data.hasExtra("UserName"))
                    mUserNameEt.setText( data.getStringExtra("UserName"));
                if(data!= null && data.hasExtra("Password"))
                    mPasswordEt.setText( data.getStringExtra("Password"));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setStatusBar(R.color.common_bg);
    }
}
